import http from "./utils/request";
import { getCityList } from "./api/index";

App({
  onLaunch() {
    // 获取当前用户的地理位置
    wx.getLocation({
      success: async (res) => {
        // console.log("success", res);
        // 主要有两个字段： res.latitude(纬度) res.longitude(经度)

        // 调用腾讯地图接口获取到城市信息
        const resp = await http({
          url: "https://apis.map.qq.com/ws/geocoder/v1/",
          method: "GET",
          data: {
            key: "W6ABZ-T4Q65-7BWIH-IXR4V-TXG5Z-C4FJW", // 开发密钥
            location: `${res.latitude},${res.longitude}`, // 经纬度
          },
        });
        let cityName = resp.result.address_component.city;
        cityName = cityName.substr(0, cityName.length - 1);
        // console.log(cityName);

        // 调用城市列表接口，获取到所有的城市数据
        const {
          data: { cities },
        } = await getCityList();
        // cities 给储存起来
        wx.setStorageSync('cities', cities)
        // console.log("cities", cities);

        // 使用 city 到 cities 查找城市
        const city = cities.find((item) => item.name === cityName);
        // 将 city 给储存起来
        wx.setStorageSync("city", city);
      },
    });
  },
});
